/*
 * Copyright (c) 2007, TopCoder, Inc. All rights reserved.
 */

using System;
using System.Collections.Generic;

namespace TopCoder.Util.Calendar.Entry
{
    /// <summary>
    /// <para>This class implements the <c>IComparer&lt;BaseCalendarEntity&gt;</c> interface.</para>
    /// <para>
    /// It will compare <c>BaseCalendarEntry</c> instances on the <c>BaseCalendarEntry.Type.TypeId</c>
    /// field and could be used to sort calendar entries by <c>BaseCalendarEntry.Type.TypeId</c> field in
    /// ascending order.
    /// </para>
    /// </summary>
    /// <remarks>
    /// Thread Safety: This class is thread safe since it's immutable.
    /// </remarks>
    ///
    /// <author>snower, fuyun</author>
    /// <version>1.0</version>
    /// <copyright>Copyright (c) 2007, TopCoder, Inc. All rights reserved.</copyright>
    public class CalendarEntryTypeComparer : IComparer<BaseCalendarEntry>
    {
        /// <summary>
        /// Creates a new <c>CalendarEntryTypeComparer</c> instance.
        /// </summary>
        public CalendarEntryTypeComparer()
        {
        }

        /// <summary>
        /// <para>
        /// Compares two calendar entries on the <c>BaseCalendarEntry.Type.TypeId</c> field and
        /// returns a value indicating whether one is less than, equal to, or greater than the other.
        /// </para>
        /// <para>
        /// Note: null entry is acceptable and considered less then any other entry.
        /// </para>
        /// </summary>
        /// <param name="x">the first calendar entry to compare.</param>
        /// <param name="y">the second calendar entry to compare.</param>
        /// <returns>
        /// Less than zero -- x is less than y. Zero -- x equals y. Greater than zero -- x is greater than y.
        /// </returns>
        /// <exception cref="ArgumentException">If the Type field of the given parameter is null.</exception>
        public int Compare(BaseCalendarEntry x, BaseCalendarEntry y)
        {
            // check if the type is null
            if (x != null && x.Type == null)
            {
                throw new ArgumentException("The argument x could not have null type.", "x");
            }
            if (y != null && y.Type == null)
            {
                throw new ArgumentException("The argument y could not have null type.", "y");
            }

            // compare if x or y is null.
            int rst = CalendarHelper.compare(x, y);
            if (rst == int.MaxValue)
            {
                // x and y are both not null, compare the type id.
                return x.Type.TypeId.CompareTo(y.Type.TypeId);
            }

            return rst;
        }
    }
}